﻿function Settings() {

    var self = this;

    var fallback = {};

    function getItem(key) {
        if (localStorage) {
            var res = localStorage.getItem(key);
            return res;
        }
        return fallback[key];
    }

    function getObject(key) {
        var res = getItem(key);
        if (!res) return null;
        try {
            return JSON.parse(res);
        } catch (e) {
            return null;
        }
    }

    function setItem(key, value) {
        if (localStorage) {
            localStorage.setItem(key, value);
            return;
        }
        fallback[key] = value;
    }

    function setObject(key, value) {
        setItem(key, JSON.stringify(value));
    }

    function removeItem(key) {
        if (localStorage) {
            localStorage.removeItem(key);
            return;
        }
        delete fallback[key];
    }

    function folder(name) {
        return new FolderSettings(self, name);
    }

    this.getItem = getItem;
    this.setItem = setItem;
    this.getObject = getObject;
    this.setObject = setObject;
    this.removeItem = removeItem;
    this.folder = folder;
}

function FolderSettings(parent, prefix) {

    var self = this;
    
    function childrenCreated(name) {
        var children = getObject('__children') || {};
        children[name] = '1';
        setObject('__children', children);
    }

    function childrenRemoved(name) {
        var children = getObject('__children') || {};
        delete children[name];
        setObject('__children', children);
    }

    function getItem(key) {
        return parent.getItem(prefix + '.' + key);
    }

    function getObject(key) {
        return parent.getObject(prefix + '.' + key);
    }

    function setItem(key, value) {
        childrenCreated(key);
        parent.setItem(prefix + '.' + key, value);
    }

    function setObject(key, value) {
        if (key != '__children') {
            childrenCreated(key);
        }
        parent.setObject(prefix + '.' + key, value);
    }

    function removeItem(key) {
        childrenRemoved(key);
        parent.removeItem(prefix + '.' + key);
    }

    function folder(name) {
        childrenCreated(name);
        return new FolderSettings(parent, prefix + '.' + name);
    }

    function removeFolder() {
        var children = getObject('__children') || {}; //todo: recursive?
        for (var key in children) {
            removeItem(key);
        }
        //todo: remove __children
    }

    this.getItem = getItem;
    this.setItem = setItem;
    this.getObject = getObject;
    this.setObject = setObject;
    this.removeItem = removeItem;
    this.folder = folder;
    this.removeFolder = removeFolder;
}